package cn.itcast.controller;

import cn.itcast.entity.Result;
import cn.itcast.massage.MessageConstant;
import cn.itcast.massage.RedisMessageConstant;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map){
        // 将前端返回的验证码跟redis中的验证码进行比对
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String validate_Code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCode!=null&&validate_Code!=null&&validateCode.equals(validate_Code)){
            // 验证码校验成功,调用service查看此用户是否为会员,如果不是则自动注册为会员
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
                // 不是会员,自动注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }

            // 存进cookie
            Cookie cookie = new Cookie("login_tel",telephone);
            // 设置cookie作用域,跨包获取cookie
            cookie.setPath("/");
            // 设置cookie时限为30天
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);

            // 将会员信息保存到redis,时限为30分钟
            jedisPool.getResource().setex(telephone,60*30,member.toString());
        }else {
            // 验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
